<template>
	<page-meta :page-style="show ? 'overflow: hidden;' : ''"></page-meta>
	<view class="container">
		<u-popup :show="show" @close="close" mode="right" :duration="100" :closeOnClickOverlay="false">
			<view class="container-popup">
				<!-- 1. 自定义导航栏 -->
				<view class="custom-navbar" :style="{ paddingTop: (statusBarHeight * 2) + 'rpx' }">
					<view class="nav-left">
						<u-icon name="arrow-left" size="22" @click="close"></u-icon>
						<u-avatar v-if="postDetail.avatar" :src="postDetail.avatar" size="30"
							customStyle="margin: 0 16rpx;" mode="aspectFill"></u-avatar>
						<view class="author-info-nav">
							<text class="author-name">{{ postDetail.nickName || '加载中...' }}</text>
							<!-- <view class="author-tag">
								<image src="/static/index/local/icon_gjtz.png" mode="heightFix"></image>
								<text>{{authorInfo.tag}}</text>
							</view> -->
						</view>
					</view>
					<view class="nav-right">
						<view class="level-right" v-if="!isFollowed" @click.stop="onFollow()">
							<u-icon name="plus" class="icon" :plain="true" size="14" shape="circle"
								color="#FE4E4E"></u-icon>关注
						</view>
						<view class="level-right active" v-if="isFollowed" @click.stop="onFollow()">
							<u-icon name="checkmark" class="icon" :plain="true" size="14" shape="circle"
								color="#ccc"></u-icon>已关注
						</view>
						<u-icon name="share-square" size="22" customStyle="margin-left: 20rpx;"></u-icon>
					</view>
				</view>

				<scroll-view class="main-content" scroll-y="true">
					<!-- 顶部媒体轮播 -->
					<view class="media-swiper-container">
						<u-swiper v-if="mediaList.length > 0" :list="mediaList" keyName="url"
							@change="e => swiperCurrent = e.current" :autoplay="false" indicator indicatorMode="dot"
							:height="swiperHeight" imgMode="aspectFit" radius="0" indicatorStyle="bottom:20rpx;"
							:lazy-load="true" :load-when-needed="true" indicatorActiveColor="#ffaa0c">
						</u-swiper>

						<!-- 轮播图骨架屏 -->
						<u-skeleton v-else rows="0" title :avatar="false" loading height="1000rpx" titleHeight="450rpx"
							titleWidth="100%">
						</u-skeleton>
						<view class="swiper-indicator">{{ swiperCurrent + 1 }}/{{ mediaList.length }}</view>
					</view>

					<!-- 帖子内容 -->
					<view class="post-content-wrapper">
						<view class="post-title">{{ postDetail.title || '' }}</view>
						<view class="post-text">
							<text>{{ postDetail.content }}</text>
						</view>

						<view class="tags-section" v-if="postDetail.postTopics && postDetail.postTopics.length > 0">
							<text class="tag-item" v-for="(tag, index) in postDetail.postTopics"
								:key="index">#{{ tag.title }}</text>
						</view>

						<!-- 消费凭证 -->
						<view class="consumption-voucher" v-if="postDetail.isGood == 0">
							<view class="consumption-voucher-left">
								<view class="consumption-voucher-left-top">
									消费凭证
								</view>
								<view class="consumption-voucher-left-bottom">
									已通过平台审核，可作为参考
								</view>
							</view>

							<view class="consumption-voucher-right">
								<view class="consumption-voucher-right-show">
									<image src="/static/index/showDemo.png" mode=""></image>
									<view class="consumption-voucher-right-show-search">
										<u-icon name="search" color="rgba(255, 255, 255, 1)" size="26rpx"></u-icon>
									</view>
								</view>
								<view class="consumption-voucher-right-add">
									<image src="/static/index/addDemo.png" mode=""></image>
									<view class="consumption-voucher-right-show-add">
										+5
									</view>
								</view>
							</view>
						</view>

						<view class="publish-info">
							<text>发布于 {{ formatDate(postDetail.createTime) }}</text>
							<text class="location-text">{{ formatLocation(postDetail.location) }}</text>
						</view>
					</view>

					<!-- 打赏模块 -->
					<view class="tip">
						<!-- 		<view class="tip-top-img">
							<image src="/static/tip/tip-header.png" mode=""></image>
						</view> -->
						<view class="tip-top-title">
							“您的鼓励，是我的动力”
						</view>
						<!-- <view class="tip-middle">
							<view class="tip-middle-left" v-for="(tipListItem,index) in tipList" :key="index">
								<image src="/static/logo.png" mode=""></image>
							</view>
							<view class="tip-middle-right" v-if="tipList.length > 0">
								<view class="tip-middle-right-left">
									{{ tipList.length + '+' }}
								</view>
								<view class="tip-middle-right-right">人打赏</view>
							</view>
						</view> -->
						<view class="tip-footer">
							打赏
						</view>
					</view>

					<!-- 猜你也想去 -->
					<view class="highlight-section"
						v-if="postDetail.clientSpotsList &&postDetail.clientSpotsList.length > 0">
						<view class="section-title">
							<text class="section-title-text">猜你也想去</text>
							<text class="indexIconFont icon-xzms-cnyxq"></text>
							<text class="indexIconFont icon-xzms-cnyxq-xhx"></text>
						</view>
						<view class="highlight-list">
							<view class="highlight-item" v-for="item in postDetail.clientSpotsList" :key="item.id"
								@click="handleToAdress(item)">
								<image :src="item.imgUrl" mode="aspectFill" class="item-image" :lazy-load="true"
									@load="onImageLoad(`highlight-${item.id}`)"
									@error="onImageError(`highlight-${item.id}`)">
								</image>
								<view class="item-info">
									<view class="item-title-row">
										<text class="item-title">{{ item.spotName }}</text>
										<u-tag v-if="item.tag" :text="item.tag.text" :borderColor="item.tag.borderColor"
											color="#fa3534" size="mini" shape="circle" plain></u-tag>
									</view>
									<view class="item-distance">
										<text class="indexIconFont icon-dw"></text>
										<view class="distance">
											距你{{ item.distance || '未知' }}
										</view>
									</view>
									<!-- <text class="item-related">相关帖子 {{ item.relatedPosts }}+</text> -->
									<view class="item-address">
										<view class="address">
											地址：{{ item.address }}
										</view>
										<u-icon name="arrow-right" color="#cccccc" size="16"></u-icon>
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 评论区 -->
					<view class="comment-section" id="comment-section">
						<view class="section-title comment-title">
							<text>评论 {{ tableTotal }}</text>
							<view class="view-count">
								<u-icon name="eye" color="#999" size="16"></u-icon>
								<text>浏览量 {{ postDetail.viewCount | formatLikes }}</text>
							</view>
						</view>

						<view v-for="(item,index) in tableData" :key="index" class="comment-view"
							@click="openComment(item)">
							<view class="comment-view-header">
								<view class="comment-view-header-left">
									<view class="comment-view-header-avatar">
										<image :src="item.user_avatar?item.user_avatar:'/static/userAvatar.png'"
											mode=""></image>
									</view>
									<view class="comment-view-header-user_name">
										{{item.user_name}}
									</view>
									<view class="comment-view-header-tags" v-show="item.user_id == postDetail.userId">
										作者
									</view>
								</view>

								<view class="comment-view-header-right" @click="likeFun(item)">
									<u-icon :name="item.is_like == 1 ? 'heart-fill' : 'heart'"
										:color="item.is_like == 1 ? '#ff5050' : '#666'" size="14"></u-icon>
								</view>
							</view>
							<view class="comment-view-content">
								<view class="comment-view-content-left">
									{{item.user_content}}
								</view>
								<view class="comment-view-content-right">
									{{item.likeCount}}
								</view>
							</view>

							<view class="comment-images-container" v-if="item.files && item.files.length > 0">
								<u-album :urls="item.files" keyName="fileUrl" multipleSize="180rpx" singleSize="180rpx"
									maxCount="3">
								</u-album>
							</view>

							<view class="comment-view-footer">
								{{formatDate(item.create_time)}}
							</view>
						</view>
						<!-- 评论输入框 -->
						<CommentInput :show="showComment" :duration="CommentDuration" :placeholder="'爱评论的人运气都不差'"
							@close="closeComment" @open="openComment" @submit="handleCommentSubmit"
							:replyTarget="replyTarget" />
					</view>
				</scroll-view>

				<!-- 底部操作栏 -->
				<view class="bottom-bar">
					<view class="input-placeholder" @click="openComment">
						<u-icon name="edit-pen" color="#999" size="18"></u-icon>
						<text>说点什么吧...</text>
					</view>
					<view class="action-icons">

						<view class="icon-item" @click="handleLikePost">
							<view class="icon-item-top">
								<image
									:src="postDetail.isLiked ?'/static/index/detail/good-active.png' :'/static/index/detail/good.png'"
									mode=""></image>
							</view>
							<view class="icon-item-bottom">{{ postDetail.likeCount | formatLikes }}</view>
						</view>

						<view class="icon-item" @click="handleUnGood">
							<view class="icon-item-top">
								<image
									:src="postDetail.isStep ?'/static/index/detail/unGood-active.png' :'/static/index/detail/unGood.png'"
									mode=""></image>
							</view>
							<view class="icon-item-bottom">{{ postDetail.stepCount | formatLikes }}</view>
						</view>

						<view class="icon-item" @click="handleCollectPost">
							<view class="icon-item-top">
								<image
									:src="postDetail.isCollected ?'/static/index/detail/star-active.png' :'/static/index/detail/star.png'"
									mode=""></image>
							</view>
							<view class="icon-item-bottom">{{ postDetail.collectCount | formatLikes }}</view>
						</view>

						<view class="icon-item">
							<view class="icon-item-top">
								<image src="/static/index/detail/share.png" mode=""></image>
							</view>
							<view class="icon-item-bottom">{{ postDetail.repostCount | formatLikes }}</view>
						</view>

					</view>
				</view>


			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		getPostDetails,
		getClientFollow,
		getCommentList,
		addComment,
		postClientLike,
		postCancelLike,
		postClientCollect,
		postCancelCollect,
		addCommentLike,
		cancelCommentLike,
		clientStep,
		deleteClientStep
	} from '@/request/api.js';
	import config from '@/config/index.js'
	import CommentInput from '@/components/commonComment/commonComment.vue';
	import CComment from "@/components/XJ-comment/index";
	export default {
		name: "richPostDetail",
		components: {
			CommentInput,
			CComment
		},
		props: {
			show: {
				type: Boolean,
				default: false,
			},
			postData: {
				type: Object,
				default: {}
			}
		},
		watch: {
			postData: {
				handler(newVal) {
					if (newVal && Object.keys(newVal).length > 0) {
						this.populatePageWithData(newVal);
						// 进入页面，主要数据是由父组件传入的，内部的评论列表需要进入后单独请求
						this.fetchComments(newVal.id);

						// 预加载首张图片以获取准确尺寸
						this.$nextTick(() => {
							if (this.mediaList.length > 0) {
								this.preloadFirstImage();
							}
						});
					}
				},
				immediate: true
			},
			show: {
				handler(newVal) {
					if (newVal) {
						// 弹窗打开时重新计算轮播图高度
						this.$nextTick(() => {
							this.calculateSwiperHeightWithImage();
						});
					}
				}
			}
		},
		filters: {
			formatLikes(val) {
				if (typeof val !== 'number') return val;
				if (val >= 10000) return (val / 10000).toFixed(1) + 'w';
				if (val >= 1000) return (val / 1000).toFixed(1) + 'k';
				return val;
			}
		},
		data() {
			return {
				statusBarHeight: 0,
				systemInfo: null, // 系统信息
				authorInfo: {},
				postDetail: {},
				isFollowed: false,
				swiperHeight: '450rpx', // 添加默认高度
				swiperCurrent: 0,
				showComment: false,
				highlightedItems: [],
				tableData: [],
				mediaList: [],
				tableTotal: 0,
				CommentDuration: 300,
				// 图片加载状态管理
				imageLoadStatus: {},
				imageCache: {}, // 图片缓存
				// 添加当前位置属性
				currentLocation: {
					longitude: null,
					latitude: null
				},
				// 打赏列表
				tipList: [],
				showUploadOptions: false,
				replyTarget: null, // 添加回复目标参数
			};
		},
		created() {
			this.systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = this.systemInfo.statusBarHeight;

			this.getCurrentLocation();
		},

		methods: {
			// 处理评论提交
			handleCommentSubmit(submitData) {
				const {
					content,
					files
				} = submitData;

				// 构建提交参数
				const params = {
					postId: Number(this.postDetail.id),
					userId: Number(this.$store.state.userInfo.userId),
					content: content,
					postCreatorId: Number(this.postDetail.userId),
					files: files,
				};

				// 调用API提交评论
				addComment(params).then(res => {
					if (res.data.code == 500) {
						uni.showToast({
							title: res.data.msg,
							icon: 'none'
						});
					} else {
						// 评论成功，刷新评论列表
						this.fetchComments(this.postDetail.id);
						this.showComment = false;
					}
				});
			},
			showToast(message, icon = 'none') {
				uni.showToast({
					title: message,
					icon,
					duration: 3000
				});
			},

			// 预加载首张图片 (替代方案)
			preloadFirstImage() {
				if (this.mediaList.length > 0) {
					// 使用 uni.getImageInfo 获取图片信息，这也会触发图片加载
					uni.getImageInfo({
						src: this.mediaList[0].url,
						success: (info) => {
							// 图片信息获取成功后重新计算高度
							this.calculateSwiperHeightWithImage();
						},
						fail: (err) => {
							console.error('获取图片信息失败:', err);
							// 即使获取信息失败也尝试计算高度
							this.calculateSwiperHeightWithImage();
						}
					});
				}
			},
			// 图片加载成功回调
			onImageLoad(key) {
				this.$set(this.imageLoadStatus, key, 'loaded');
			},

			// 图片加载失败回调
			onImageError(key) {
				this.$set(this.imageLoadStatus, key, 'error');
			},

			onFollow() {
				getClientFollow({
					userId: this.postDetail.userId
				}).then(() => {
					this.isFollowed = !this.isFollowed;
				});
			},
			async fetchComments(postId) {
				try {
					const res = await getCommentList(postId);
					this.tableTotal = Number(res.data.total) || 0;
					this.tableData = (res.data.rows || []).map(c => ({
						id: c.commentId,
						parent_id: null,
						reply_id: null,
						reply_name: null,
						user_name: c.nickName,
						user_avatar: c.avatar,
						user_content: c.content,
						is_like: c.isLiked,
						like_count: c.likeCount,
						create_time: c.createTime,
						user_id: c.userId,
						files: c.files,
						likeCount: c.likeCount,
						commentId: c.commentId

					}));
					console.log(this.tableData);
				} catch (error) {
					console.error("Fetch comments failed:", error);
				}
			},
			openComment() {
				this.CommentDuration = 600
				this.showComment = true
			},
			closeComment() {
				this.CommentDuration = 100
				this.showComment = false
			},
			close() {
				this.$emit('close');
			},
			formatLocation(locationStr) {
				if (!locationStr) return '';
				const parts = locationStr.split('-');
				return parts[0] + '-' + parts[1]; // 优先返回市，如果没有-就返回全部
			},
			formatDate(dateStr) {
				return dateStr ? dateStr.split(' ')[0].replace(/-/g, '.') : '';
			},
			populatePageWithData(postData) {
				this.postDetail = postData;
				this.isFollowed = postData.isFollowed > 0;
				this.authorInfo = {
					id: postData.userId,
					user_name: postData.nickName,
					user_avatar: postData.avatar,
					tag: '高级土著'
				};
				this.mediaList = (postData.files || []).map(file => ({
					url: file.fileUrl,
					type: file.isImage ? 'image' : 'video'
				}));
				this.tableTotal = Number(this.commentCount) || 0;

				// 计算 swiper 高度
				this.$nextTick(() => {
					this.calculateSwiperHeightWithImage();
				});

				// 处理景点列表的距离计算
				if (postData.clientSpotsList && Array.isArray(postData.clientSpotsList)) {
					postData.clientSpotsList.forEach(item => {
						if (item.ext1) {
							// 使用 $set 确保响应式更新
							this.$set(item, 'distance', this.getDistance(item.ext1));
						}
					});
				}
			},

			// 解析坐标字符串并计算距离
			getDistance(ext1) {
				// 检查参数和当前位置
				if (!ext1 || !this.currentLocation.longitude || !this.currentLocation.latitude) {
					return '未知';
				}

				try {
					// 解析目标坐标
					const coords = ext1.split(',');
					if (coords.length !== 2) {
						return '未知';
					}

					const targetLat = parseFloat(coords[1].trim());
					const targetLng = parseFloat(coords[0].trim());

					if (isNaN(targetLat) || isNaN(targetLng)) {
						return '未知';
					}

					// 计算距离
					const distance = this.calculateDistance(
						this.currentLocation.latitude,
						this.currentLocation.longitude,
						targetLat,
						targetLng
					);

					return this.formatDistance(distance);
				} catch (error) {
					console.error('计算距离出错:', error);
					return '未知';
				}
			},

			// 获取当前位置
			getCurrentLocation() {
				// 先从缓存读取
				const longitude = uni.getStorageSync('longitude');
				const latitude = uni.getStorageSync('latitude');

				if (longitude && latitude) {
					this.currentLocation = {
						longitude: parseFloat(longitude),
						latitude: parseFloat(latitude)
					};
					console.log('从缓存获取位置:', this.currentLocation);
					return;
				}

				// 缓存没有则重新获取
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						this.currentLocation = {
							longitude: res.longitude,
							latitude: res.latitude
						};
						// 存储到缓存
						uni.setStorageSync('longitude', res.longitude);
						uni.setStorageSync('latitude', res.latitude);
						console.log('获取并存储位置:', this.currentLocation);
					},
					fail: (err) => {
						console.log('获取位置失败:', err);
						// 设置默认位置或标记为未知
						this.currentLocation = {
							longitude: null,
							latitude: null
						};
					}
				});
			},
			// 计算两点间距离（使用 Haversine 公式）
			calculateDistance(lat1, lon1, lat2, lon2) {
				const R = 6371; // 地球半径（公里）
				const dLat = this.toRadians(lat2 - lat1);
				const dLon = this.toRadians(lon2 - lon1);
				const a =
					Math.sin(dLat / 2) * Math.sin(dLat / 2) +
					Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
					Math.sin(dLon / 2) * Math.sin(dLon / 2);
				const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				const d = R * c;
				return d;
			},
			// 角度转弧度
			toRadians(degrees) {
				return degrees * (Math.PI / 180);
			},

			// 格式化距离显示
			formatDistance(distance) {
				if (distance === null || distance === undefined) {
					return '未知';
				}

				if (distance < 1) {
					// 小于1公里显示米
					return Math.round(distance * 1000) + 'm';
				} else if (distance < 10) {
					// 1-10公里保留一位小数
					return distance.toFixed(1) + 'km';
				} else {
					// 大于10公里取整
					return Math.round(distance) + 'km';
				}
			},
			async fetchPostDetails(postId) {
				try {
					const res = await getPostDetails(postId);
					if (res.data && res.data.data) {
						this.populatePageWithData(res.data.data);
					}
				} catch (error) {
					console.error("Fetch post details failed:", error);
				}
			},

			handleToAdress(item) {
				// 解析目标坐标
				const coords = item.ext1.split(',');
				if (coords.length !== 2) {
					return '未知';
				}
				const targetLat = parseFloat(coords[1].trim());
				const targetLng = parseFloat(coords[0].trim());
				uni.openLocation({
					latitude: targetLat, //纬度
					longitude: targetLng, //经度
					name: item.spotName,
					address: ""
				});
			},

			handleCollectPost() {
				const isCollected = this.postDetail.isCollected;
				const api = isCollected ? postCancelCollect : postClientCollect;

				this.postDetail.isCollected = !isCollected;
				this.postDetail.collectCount += isCollected ? -1 : 1;

				api(this.postDetail.id).catch(() => {
					this.postDetail.isCollected = isCollected;
					this.postDetail.collectCount += isCollected ? 1 : -1;
				});
			},

			handleLikePost() {
				const isLiked = this.postDetail.isLiked;
				const api = isLiked ? postCancelLike : postClientLike;

				// UI即时反馈
				this.postDetail.isLiked = !isLiked;
				this.postDetail.likeCount += isLiked ? -1 : 1;

				api({
					postId: this.postDetail.id,
					userId: this.$store.state.userInfo.userId
				}).catch(() => {
					// 失败时回滚
					this.postDetail.isLiked = isLiked;
					this.postDetail.likeCount += isLiked ? 1 : -1;
				});
			},
			handleUnGood() {
				const isStep = this.postDetail.isStep;
				const api = !isStep ? clientStep : deleteClientStep;

				// UI即时反馈
				this.postDetail.isStep = !isStep;
				this.postDetail.stepCount += isStep ? -1 : 1;

				api({
					postId: this.postDetail.id,
					userId: this.$store.state.userInfo.userId
				}).catch(() => {
					// 失败时回滚
					this.postDetail.isStep = isStep;
					this.postDetail.likeCount += isStep ? 1 : -1;
				});
			},
			handleLikeComment() {

			},

			// 点赞评论
			likeFun(params) {
				console.log(params);
				if (params.is_like == 0) {
					addCommentLike(params.commentId).then(res => {
						if (res.data.code != 200) {} else {
							this.fetchComments(this.postDetail.id);
						}
					})
				} else {
					cancelCommentLike(params.commentId).then(res => {
						if (res.data.code != 200) {} else {
							this.fetchComments(this.postDetail.id);
						}
					})
				}
			},

			// 回复评论
			replyFun(params, callback) {
				let data = {
					postId: new Number(this.postId),
					userId: new Number(this.$store.state.userInfo.userId),
					parentId: new Number(params.params.parent_id) || null,
					replyToUserId: new Number(params.params.reply_id) || null,
					content: params.params.user_content || null,
					postCreatorId: new Number(this.postCreatorId)
				}
				addComment(data).then((res) => {
					if (res.data.code == 500) {
						uni.$u.toast(res.data.msg);
					} else {
						// const data = { id: Math.random(res.data.data.commentId ) };
						const data = {
							id: res.data.data.commentId
						}; // 很重要的回参! 必须拿到后端返回评论id! 删除需要!
						callback(data); // 目前为了展示效果, 直接执行callback
					}
				});
			},

			sendParent(type) {
				// 触发父页面监听的 "returnData" 事件，回传数据
				const eventChannel = this.getOpenerEventChannel();
				eventChannel.emit('returnData', {
					id: this.postId,
					userId: this.authorInfo.id,
					type: type,
					isLiked: this.postDetail.isLiked,
					likeCount: this.postDetail.likeCount,
					isCollected: this.postDetail.isCollected,
					collectCount: this.postDetail.collectCount,
					isFollowed: this.postDetail.isFollowed
				});
			},

			// 删除评论
			deleteFun({
				params,
				mode
			}, callback) {
				// 当请求成功, 调用callback执行评论删除;
				switch (this.deleteMode) {
					case "bind":
						// 逻辑: 调用接口进行评论内容修改 update
						setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
						break;
					case "only":
						// 逻辑: 调用接口删除一个评论 delete
						setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
						break;
					default:
						// all
						// 逻辑: 调用接口删除多个评论 [delete]
						// Demo如下:
						// let datas = {
						// 	commentId:
						// 	postId:
						// 	parentId:
						// 	replyCount:
						// }
						// removeComment()
						// axios.post("http://xxx/delete", { ids: params }).then((res) => {
						//   if (res.code === 0) {
						//     callback(res);
						//   }
						// });
						setTimeout(() => callback(), 500); // 目前为了展示效果, 直接执行callback
						break;
				}
			},
			// 计算轮播图高度
			async calculateSwiperHeightWithImage() {
				if (this.mediaList && this.mediaList.length > 0) {
					try {
						// 使用缓存避免重复计算相同图片
						const cacheKey = `swiper-height-${this.mediaList[0].url}`;
						const cachedHeight = this.getCache(cacheKey);
						if (cachedHeight) {
							this.swiperHeight = cachedHeight;
							return;
						}

						const systemInfo = uni.getSystemInfoSync();
						const screenWidth = systemInfo.windowWidth;

						// 获取图片信息
						const imageInfo = await new Promise((resolve, reject) => {
							uni.getImageInfo({
								src: this.mediaList[0].url,
								success: resolve,
								fail: reject
							});
						});

						const imageWidth = imageInfo.width;
						const imageHeight = imageInfo.height;

						// 计算实际显示高度 (px单位)
						const imageRatio = imageHeight / imageWidth;
						let displayHeight = screenWidth * imageRatio;

						// 转换为rpx并应用限制
						let finalHeight = displayHeight * 2; // px转rpx

						// 应用高度限制 (调整为更合理的范围)
						const heightLimits = {
							min: 400, // 200px
							max: 1000 // 500px
						};

						if (finalHeight < heightLimits.min) {
							finalHeight = heightLimits.min;
						} else if (finalHeight > heightLimits.max) {
							finalHeight = heightLimits.max;
						}

						this.swiperHeight = finalHeight + 'rpx';
						// 缓存计算结果
						this.setCache(cacheKey, this.swiperHeight);
					} catch (error) {
						// 使用默认固定高度
						this.swiperHeight = '600rpx';
					}
				}
			},
			// 简单的缓存机制
			getCache(key) {
				try {
					const cache = uni.getStorageSync('image-cache') || {};
					return cache[key];
				} catch (e) {
					return null;
				}
			},

			setCache(key, value) {
				try {
					const cache = uni.getStorageSync('image-cache') || {};
					cache[key] = value;
					uni.setStorageSync('image-cache', cache);
				} catch (e) {
					// 忽略缓存错误
				}
			}
		},
	};
</script>

<style lang="scss" scoped>
	.container {
		.container-popup {
			width: 100vw;
			height: 100vh;
			display: flex;
			flex-direction: column;

			.custom-navbar {
				height: 90rpx;
				flex-shrink: 0;
				position: fixed;
				top: 0;
				left: 0;
				right: 0;
				z-index: 9999;
				background-color: rgba(255, 255, 255, 0.9);
				backdrop-filter: blur(10rpx);
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 0 30rpx;

				/* 防止被键盘影响的样式 */
				transform: translateZ(0);
				will-change: transform;
				-webkit-transform: translate3d(0, 0, 0);
				-webkit-backface-visibility: hidden;
				-webkit-perspective: 1000rpx;

				.nav-left {
					display: flex;
					align-items: center;

					.author-info-nav {
						display: flex;
						flex-direction: column;

						.author-name {
							font-size: 28rpx;
							font-weight: 500;
						}

						.author-tag {
							display: flex;
							align-items: center;

							image {
								height: 24rpx;
								margin-right: 6rpx;
							}

							text {
								font-size: 20rpx;
								color: #f81217;
							}
						}
					}
				}

				.nav-right {
					display: flex;
					align-items: center;

					.level-right {
						display: flex;
						color: #FE4E4E;
						border: 1rpx solid #FE4E4E;
						border-radius: 50rpx;
						font-size: 26rpx;
						padding: 5rpx 15rpx;

						.icon {
							margin-right: 5rpx;
						}
					}

					.active {
						color: #cccccc;
						border: 1rpx solid #cccccc;
					}
				}
			}

			.main-content {
				flex: 1;
				margin-top: 162rpx;
				height: calc(100vh - 162rpx); // 添加明确高度

				.media-swiper-container {
					width: 100%;
					position: relative;
					background-color: red;

					.u-swiper {
						width: 100%;
					}

					.swiper-indicator {
						position: absolute;
						top: 60rpx;
						right: 30rpx;
						background-color: rgba(120, 120, 130, 1);
						color: #fff;
						font-size: 24rpx;
						padding: 4rpx 16rpx;
						border-radius: 20rpx;
					}
				}

				.post-content-wrapper {
					background-color: #fff;
					padding: 30rpx;
					border-start-end-radius: 40rpx;
					border-start-start-radius: 40rpx;
					margin-top: 20rpx;
					position: relative;

					.post-title {
						font-size: 34rpx;
						font-weight: bold;
						margin-bottom: 20rpx;
					}

					.post-text {
						font-size: 30rpx;
						line-height: 1.7;
					}

					.tags-section {
						margin: 30rpx 0;

						.tag-item {
							color: #507daf;
							margin-right: 20rpx;
						}
					}


					// 消费凭证样式
					.consumption-voucher {
						background-color: rgba(248, 248, 248, 1);
						width: 100%;
						height: 100rpx;
						border-radius: 20rpx;
						display: flex;
						justify-content: space-between;
						box-sizing: border-box;
						margin-top: 20rpx;

						.consumption-voucher-left {
							height: 76rpx;
							margin-left: 24rpx;
							margin-top: 12rpx;

							.consumption-voucher-left-top {
								font-size: 28rpx;
								font-weight: 400;
								line-height: 36rpx;
								color: rgba(0, 0, 0, 1);
							}

							.consumption-voucher-left-bottom {
								font-size: 22rpx;
								font-weight: 400;
								line-height: 36rpx;
								color: rgba(120, 120, 130, 1);
							}
						}

						.consumption-voucher-right {
							display: flex;
							height: 76rpx;
							margin-right: 24rpx;
							margin-top: 12rpx;

							.consumption-voucher-right-show {
								position: relative;
								width: 80rpx;
								height: 80rpx;
								margin-right: 18rpx;

								image {
									width: 100%;
									height: 100%;
								}

								.consumption-voucher-right-show-search {
									position: absolute;
									top: 50%;
									left: 50%;
									transform: translate(-50%, -50%);
									width: 26rpx;
									height: 26rpx;
									display: flex;
									align-items: center;
									justify-content: center;
								}
							}

							.consumption-voucher-right-add {
								position: relative;
								width: 80rpx;
								height: 80rpx;

								image {
									width: 100%;
									height: 100%;
								}

								.consumption-voucher-right-show-add {
									position: absolute;
									top: 50%;
									left: 50%;
									transform: translate(-50%, -50%);
									width: 26rpx;
									height: 26rpx;
									display: flex;
									align-items: center;
									justify-content: center;
									font-size: 26rpx;
									font-weight: 700;
									color: #fff;
								}
							}
						}
					}




					.publish-info {
						font-size: 24rpx;
						color: #4D4D56;
						display: flex;
						align-items: center;
						margin-top: 40rpx;

						.location-text {
							margin: 0 15rpx;
						}

						.dislike-btn {
							margin-left: auto;
							display: flex;
							align-items: center;

							text {
								margin-left: 5rpx;
							}
						}
					}
				}

				// 打赏
				.tip {
					display: flex;
					flex-direction: column;
					align-items: center;

					.tip-top-img {
						width: 160rpx;
						height: 120rpx;

						image {
							width: 100%;
							height: 100%;
						}
					}

					.tip-top-title {
						margin-top: 30rpx;
						font-weight: 400;
						font-size: 30rpx;
						line-height: 24rpx;
						color: #4d4d56;
					}

					.tip-middle {
						display: flex;
						justify-content: center;
						align-items: center;
						width: 100%;
						margin-top: 30rpx;

						.tip-middle-left {
							width: 44rpx;
							height: 44rpx;
							flex-shrink: 0; // 防止收缩

							image {
								border-radius: 50%;
								width: 100%;
								height: 100%;
							}

							&:not(:first-child) {
								margin-left: 10rpx;
							}
						}

						.tip-middle-right {
							display: flex;
							font-size: 24rpx;
							font-weight: 400;
							white-space: nowrap; // 不换行
							flex-shrink: 0; // 不收缩
							margin-left: 10rpx;

							.tip-middle-right-left {
								color: rgba(252, 80, 36, 1);
							}

							.tip-middle-right-right {
								color: rgba(77, 77, 86, 1);
							}
						}
					}

					.tip-footer {
						width: 110rpx;
						height: 50rpx;
						font-size: 30rpx;
						line-height: 50rpx;
						font-weight: bold;
						color: rgba(255, 255, 255, 1);
						background-color: rgba(254, 119, 46, 1);
						border-radius: 20rpx;
						text-align: center;
						margin-top: 30rpx;
					}
				}

				.highlight-section,
				.comment-section,
				.recommendation-section {
					margin-top: 16rpx;
					background-color: #fff;
					padding: 30rpx;
					position: relative;

					.section-title {
						display: flex;
						align-items: center;
						font-size: 32rpx;
						font-weight: bold;
						margin-bottom: 30rpx;
						position: relative;
						z-index: 2;
					}

					.section-title-text {
						position: relative;
						z-index: 2;
					}

					.icon-xzms-cnyxq {
						position: absolute;
						color: #000;
						z-index: 2;
						font-size: 50rpx;
						left: 150rpx;
						bottom: 0;

					}

					.icon-xzms-cnyxq-xhx {
						position: absolute;
						color: #F6DD3A;
						z-index: 1;
						left: 0;
						bottom: -10rpx;
					}

					.highlight-list {
						background-color: #f8f8f8;

						.highlight-item {
							display: flex;
							align-items: center;
							margin-bottom: 40rpx;
							position: relative;
							overflow: hidden;
							z-index: 0;
							background-color: #ffffff;
							padding-right: 24rpx;
							box-shadow: 0 0 30rpx rgba(0, 0, 0, 0.05);
							transition: all 0.2s ease-in-out;

							&:last-child {
								margin-bottom: 0;
							}

							&:active {
								transform: scale(0.98);
								box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.08);
							}

							&:last-child {
								margin-bottom: 0;
							}

							&::before {
								content: '';
								position: absolute;

								top: 0;
								right: 0;

								width: 300rpx;
								height: 100%;

								background-image: radial-gradient(circle at 0% 100%,
										transparent 40%,
										rgba(249, 248, 216, 0.5) 80%,
										rgba(232, 243, 209, 0.5) 100%);

								transform: rotate(0deg) scale(1);
								transform-origin: top right;

								z-index: 1;
							}

							.item-image,
							.item-info,
							.u-icon {
								position: relative;
								z-index: 2;
							}

							.item-image {
								width: 200rpx;
								height: 160rpx;
								border-radius: 24rpx;
								margin-right: 20rpx;
							}

							.item-info {
								flex: 1;
								display: flex;
								flex-direction: column;

								.item-title-row {
									display: flex;
									align-items: center;
									justify-content: space-between;
									margin: 8rpx 0;

									.item-title {
										font-size: 28rpx;
										font-weight: 500;
										margin-right: 10rpx;
									}
								}

								.item-distance,
								.item-related,
								.item-address {
									display: flex;
									align-items: center;
									font-size: 24rpx;
									color: #999;
									line-height: 1.8;

									.icon-dw {
										color: #f81217;
									}

									.address {
										width: 380rpx;
										white-space: nowrap;
										overflow: hidden;
										text-overflow: ellipsis;
									}

									.distance {
										margin-left: 10rpx;
									}
								}
							}
						}
					}

				}

				.commentPopup {
					padding: 20rpx 40rpx;
					margin-bottom: 20rpx;

					.commentPopup-input {
						background-color: #f5f5f5;
						border-radius: 20rpx;

						.textArea {
							background-color: #f5f5f5;
							border-radius: 20rpx;
						}

						.commentPopup-upLoad {
							margin-left: 20rpx;

							::v-deep .u-upload__wrap {
								display: flex;
								flex-wrap: nowrap;
								overflow-x: auto;

								::v-deep .u-upload__item {
									flex-shrink: 0;
									margin-right: 10rpx;
								}
							}
						}
					}

					.commentPopup-footer {
						display: flex;
						justify-content: flex-end;
						/* 右对齐 */
						margin-top: 20rpx;

						/* 左侧留空占位符（如果需要） */
						.commentPopup-footer-operation {
							flex: 1;
							display: flex;

							.commentPopup-footer-operation-first {
								width: 50rpx;
								height: 50rpx;

								image {
									width: 50rpx;
									height: 50rpx;
								}
							}

							.commentPopup-footer-operation-second {
								margin-left: 40rpx;
								width: 50rpx;
								height: 50rpx;

								image {
									width: 50rpx;
									height: 50rpx;
								}
							}
						}

						.commentPopup-footer-emitBtn {
							width: 120rpx;
						}
					}
				}

				.more-comments {
					text-align: center;
					color: #507daf;
					font-size: 26rpx;
					padding-top: 30rpx;
					display: flex;
					align-items: center;
					justify-content: center;

					text {
						margin-right: 5rpx;
					}
				}

				.comment-section {
					border-end-end-radius: 40rpx;
					border-end-start-radius: 40rpx;
				}

				.comment-section .comment-title {
					justify-content: space-between;

					.view-count {
						display: flex;
						align-items: center;
						font-size: 24rpx;
						color: #999;
						font-weight: normal;
					}
				}

				.comment-view {
					margin-bottom: 100rpx;

					.comment-view-header {
						display: flex;
						justify-content: space-between;
						height: 60rpx;
						line-height: 60rpx;

						.comment-view-header-left {
							display: flex;

							.comment-view-header-avatar {
								width: 60rpx;
								height: 60rpx;
								margin-right: 12rpx;

								image {
									border-radius: 50%;
									width: 60rpx;
									height: 60rpx;
								}
							}

							.comment-view-header-user_name {
								font-weight: 400;
								font-size: 26rpx;
								color: rgba(25, 41, 28, 1);
								margin-right: 12rpx;
							}

							.comment-view-header-tags {
								background-color: rgba(246, 221, 58, 0.7);
								min-width: 60rpx;
								text-align: center;
								border-radius: 40rpx;
								font-weight: 500;
								font-size: 11rpx;
								height: 30rpx;
								line-height: 30rpx;
								margin-top: 15rpx;
							}
						}

						.comment-view-header-right {
							display: flex;
							width: 80rpx;
							text-align: center;
							align-items: center;
							justify-content: center;

							.comment-view-header-right-red {
								font-size: 24rpx;
								line-height: 60rpx;
							}

							.comment-view-header-right-grey {
								font-size: 24rpx;
								line-height: 60rpx;
							}
						}

					}

					.comment-view-content {
						display: flex;
						justify-content: space-between;

						.comment-view-content-left {
							line-height: 40rpx;
							width: calc(100% - 180rpx);
							margin-left: 70rpx;
							font-size: 24rpx;
							font-weight: 400;
							color: rgba(25, 41, 28, 1);
						}

						.comment-view-content-right {
							width: 80rpx;
							color: rgba(77, 77, 86, 1);
							font-size: 24rpx;
							font-weight: 400;
							text-align: center;
						}
					}

					.comment-images-container {
						margin: 20rpx 0 20rpx 70rpx;
					}

					.comment-view-footer {
						color: rgba(25, 41, 28, 0.6);
						font-size: 18rpx;
						font-weight: 400;
						margin-left: 70rpx;
					}
				}
			}

			.bottom-bar {
				height: 100rpx;
				flex-shrink: 0;
				position: fixed;
				bottom: 0;
				left: 0;
				right: 0;
				background-color: #fff;
				border-top: 1rpx solid #f0f0f0;
				display: flex;
				align-items: center;
				padding: 0 30rpx;
				padding-bottom: constant(safe-area-inset-bottom);
				padding-bottom: env(safe-area-inset-bottom);
				z-index: 999;

				.input-placeholder {
					flex: 1;
					height: 72rpx;
					background-color: #f4f4f4;
					border-radius: 36rpx;
					display: flex;
					align-items: center;
					padding: 0 24rpx;
					font-size: 28rpx;
					color: #999;

					text {
						margin-left: 10rpx;
					}
				}

				.action-icons {
					display: flex;
					align-items: center;
					margin-left: 20rpx;

					.icon-item {
						margin-left: 10rpx;
						font-size: 24rpx;
						color: #333;
						display: flex;
						flex-direction: column;
						align-items: center;
						width: 80rpx; // 固定宽度

						.icon-item-top {
							width: 48rpx;
							height: 48rpx;

							image {
								width: 100%;
								height: 100%;
							}
						}

						.icon-item-bottom {
							text-align: center;
							width: 100%;
							font-size: 20rpx;
							margin-top: 4rpx;
							overflow: hidden;
							text-overflow: ellipsis;
						}
					}
				}
			}
		}
	}
</style>